#ifndef NET_THREADPOOL_H
#define NET_THREADPOOL_H

#include <functional>
#include <atomic>
#include <unordered_map>
#include <queue>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <future>

class ThreadPool {
public:
    typedef std::function<void()> Task;

    ThreadPool(uint32_t num = 5)
    {
        if (num > maxThreadNum) num = maxThreadNum;
        threadNum = num;
    }

    ~ThreadPool()
    {
        Stop();
    }

    void Start()
    {
        isStop = false;
        while (threadList.size() < threadNum) {
            threadList.emplace_back([this] {
                while (!isStop) {
                    Task task;
                    {
                        std::unique_lock<std::mutex> lock(mutex);
                        condition.wait(lock, [this] {
                            return this->isStop || !taskQueue.empty();
                        });
                        if (isStop && taskQueue.empty()) {
                            return;
                        }
                        task = std::move(taskQueue.front());
                        taskQueue.pop();
                    }
                    task();
                }
            });
        }
    }

    void Stop()
    {
        isStop = true;
        condition.notify_all();
        for (auto &td: threadList) {
            if (td.joinable()) {
                td.join();
            }
        }
    }

    template<typename F, typename ...Args>
    auto Commit(F &&f, Args &&...args) -> std::future<decltype(f(args...))>
    {
        if (isStop) Start();
        using RetType = decltype(f(args...));
        auto task = std::make_shared<std::packaged_task<RetType()>>(std::bind(f, std::forward<Args>(args)...));
        std::future ret = task->get_future();
        {
            std::unique_lock<std::mutex> lock(mutex);
            taskQueue.emplace([task] { (*task)(); });
        }
        condition.notify_one();
        return ret;
    }

private:
    std::mutex mutex;
    std::condition_variable condition;
    std::atomic<uint32_t> threadNum{};
    std::atomic<bool> isStop = true;
    std::queue<Task> taskQueue;
    std::vector<std::thread> threadList;
    uint32_t maxThreadNum = 10;
};


#endif //NET_THREADPOOL_H
